/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ejbs;

import dtos.FornecedorDTO;
import entities.Fornecedor;
import exceptions.EntidadeExistenteException;
import java.util.LinkedList;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.EJBException;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author Yeezus
 */
@Stateless
public class FornecedorBean {

    @PersistenceContext
    private EntityManager em;

    @EJB
    private FarmaciaBean farmaciaBean;

    public boolean existeFornecedor(String nome) {
        try {
            return em.find(Fornecedor.class, nome) != null;
        } catch (Exception e) {
            throw new EJBException(e.getMessage());
        }
    }

    public void criarFornecedor(String nome, String email) throws EntidadeExistenteException {
        try {
            if (farmaciaBean.existeFarmacia(nome)) {
                throw new EntidadeExistenteException("Farmacia ja existe");
            }

            em.persist(new Fornecedor(nome, email));
        } catch (Exception e) {
            throw new EJBException(e.getMessage());
        }
    }
    public List<FornecedorDTO> getFornecedores(){
        try {
            List<Fornecedor> fornecedores = (List<Fornecedor>) em.createNamedQuery("findAllFornecedores").getResultList();
            return copiarForncedoresParaDTO(fornecedores);
        } catch (Exception e) {
            throw new EJBException(e.getMessage());
        }
    }
    
    public List<FornecedorDTO> copiarForncedoresParaDTO(List<Fornecedor> fornecedores) {
        List<FornecedorDTO> dtos = new LinkedList<>();

        for (Fornecedor f : fornecedores) {
            dtos.add(new FornecedorDTO(f.getNome(),f.getEmail()));
        }
        return dtos;
    }    
}
